package com.army.study.component;

import com.army.study.ResourceTable;
import ohos.agp.components.*;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

import java.util.Optional;

public class SaveConfirmDialog extends CommonDialog {
    private OnCallBack onCallBack;

    public void setOnCallBack(OnCallBack onCallBack) {
        this.onCallBack = onCallBack;
    }

    public interface OnCallBack {
        void onConfirm(String name);
    }

    public SaveConfirmDialog(Context context) {
        super(context);

        Component container = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_dialog_layout_save, null, false);
        setContentCustomComponent(container);

        Optional<Display> display = DisplayManager.getInstance().getDefaultDisplay(context);
        int width = (int) (display.get().getAttributes().width * 0.3);
        int height = AttrHelper.vp2px(200, context);
        setSize(width, height);
        setCornerRadius(AttrHelper.vp2px(20, context));

        TextField letterContent = (TextField) container.findComponentById(ResourceTable.Id_tf_dialog_create_file_name);
        Button btnCancel = (Button) container.findComponentById(ResourceTable.Id_button_dialog_create_file_cancel);
        Button btnConfirm = (Button) container.findComponentById(ResourceTable.Id_button_dialog_create_file_confirm);
        btnConfirm.setEnabled(false);
        btnConfirm.setAlpha(0.5f);
        letterContent.addTextObserver((text, i, i1, i2) -> {
            if(text.isEmpty()){
                btnConfirm.setEnabled(false);
                btnConfirm.setAlpha(0.5f);
            }else{
                btnConfirm.setEnabled(true);
                btnConfirm.setAlpha(1f);
            }
        });

        btnCancel.setClickedListener(component -> {	destroy();});

        btnConfirm.setClickedListener(component -> {
            if(onCallBack!=null){
                String name = letterContent.getText();
                onCallBack.onConfirm(name);
            }
            destroy();
        });

    }
}
